/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilDevice;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Niudan;
import com.simon.mengkou.data.bean.base.NiudanSKU;
import com.simon.mengkou.future.base.OuerException;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.base.BaseNiudanFragment;
import com.simon.mengkou.ui.dialog.PlayResultDialog;
import com.simon.mengkou.utils.UtilOuer;

import java.math.BigDecimal;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/1/6.
 * desc    : 玩扭蛋界面
 */
public class NDPlayFragment extends BaseNiudanFragment {
    //消耗积分
    @Bind(R.id.play_id_score) TextView mTvScore;
    //扭蛋按钮
    @Bind(R.id.play_id_button) ImageView mIvPlay;
    //扭蛋按钮
    @Bind(R.id.play_id_border) ImageView mIvBorder;
    //扭蛋状态
    @Bind(R.id.play_id_machine_root) LinearLayout mLlMachineRoot;
    //扭蛋图片
    @Bind(R.id.play_id_niudan_image) SimpleDraweeView mSdvNiuduanImage;

    //
    @Bind(R.id.play_id_curtain) RelativeLayout mRlCurtain;
    @Bind(R.id.play_id_play_root) RelativeLayout mRlPlayRoot;


    private boolean mIsPlaying;

    private static final int NIUDAN_STATE_UNKNOWN       = 0;
    private static final int NIUDAN_STATE_ENABLE        = 1;
    private static final int NIUDAN_STATE_DISABLE       = 2;
    private int mNiudanState = NIUDAN_STATE_UNKNOWN;



    private Niudan mNiudan;
    private String mId;
    private String mImgUrl;
    private int mPrice;



    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        Bundle bundle = getArguments();
        if(bundle != null) {
            mNiudan = (Niudan) bundle.getSerializable(CstOuer.KEY.NIUDAN);
            if(mNiudan != null) {
                mId = mNiudan.getId();
                mImgUrl = mNiudan.getImage().getUrl();
                mPrice = BigDecimal.valueOf(mNiudan.getPrice())
                        .multiply(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            }
        }
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.fragment_play);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this, getView());
        setDoorVisible(false);

        //积分
        mTvScore.setText(getString(R.string.play_score, mPrice));

        UtilDevice.Device device = UtilDevice.getDevice(mActivity);
        float machineWidth = device.getWidth() - 80 * device.getDensity();
        float machineHeight = machineWidth / 0.783f;

        //扭蛋机器布局
        RelativeLayout.LayoutParams niParam = (RelativeLayout.LayoutParams) mSdvNiuduanImage.getLayoutParams();
        niParam.width = (int) (machineWidth * 0.62);
        niParam.height = (int)(machineHeight * 0.42);
        niParam.leftMargin = (int) (machineWidth * 0.19);
        niParam.topMargin = (int) (machineHeight * 0.0724);

        //扭蛋图片
        OuerApplication.mImageLoader.loadImage(mSdvNiuduanImage, mImgUrl);

        //扭蛋机按钮
        RelativeLayout.LayoutParams btnParam = (RelativeLayout.LayoutParams) mIvPlay.getLayoutParams();
        btnParam.width = (int) (machineWidth * 0.366 - 20 * device.getDensity());
        btnParam.height = btnParam.width;
        btnParam.topMargin = (int) (machineHeight * 0.569 + 10 * device.getDensity());

        //扭蛋机旋转指示圈
        RelativeLayout.LayoutParams borderParam = (RelativeLayout.LayoutParams) mIvBorder.getLayoutParams();
        borderParam.width = (int) (machineWidth * 0.366 + 46 * device.getDensity());
        borderParam.height = borderParam.width;
        borderParam.topMargin = (int) (machineHeight * 0.569 - 23 * device.getDensity());


        flyIn(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                niudanCheck();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }



    private void niudanCheck() {
        AgnettyFuture future = OuerApplication.mOuerFuture.niudanCheck(mId,
                new OuerFutureListener(mActivity) {
                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        Boolean flag = (Boolean)result.getAttach();
                        mNiudanState = flag ? NIUDAN_STATE_ENABLE : NIUDAN_STATE_DISABLE;
                        if(mNiudanState == NIUDAN_STATE_ENABLE) {
                            Animation anim01 = AnimationUtils.loadAnimation(mActivity,
                                    R.anim.moekou_play_rotate01);
                            anim01.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    Animation anim02 = AnimationUtils.loadAnimation(mActivity,
                                            R.anim.moekou_play_rotate02);
                                    mIvBorder.startAnimation(anim02);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });

                            mIvBorder.startAnimation(anim01);
                        }

                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        mNiudanState = NIUDAN_STATE_DISABLE;
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        mNiudanState = NIUDAN_STATE_UNKNOWN;
                    }
                });

        attachDestroyFutures(future);
    }


    private void niudanStart() {
        final long delay = 1500;
        final long start = System.currentTimeMillis();
        AgnettyFuture future = OuerApplication.mOuerFuture.niudanStart(mId,
                new OuerFutureListener(mActivity) {
                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        final NiudanSKU sku = (NiudanSKU)result.getAttach();
                        long time = System.currentTimeMillis() - start;
                        if( time < delay) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    stopAnim();
                                    PlayResultDialog dialog = new PlayResultDialog(mActivity, NDPlayFragment.this, sku);
                                    dialog.show();
                                }
                            }, delay - time);
                        } else {
                            stopAnim();
                            PlayResultDialog dialog = new PlayResultDialog(mActivity, NDPlayFragment.this, sku);
                            dialog.show();
                        }

                        OuerDispatcher.sendNiudanPlayBroadcast(mActivity);
                    }

                    @Override
                    public void onException(final AgnettyResult result) {
                        super.onException(result);
                        long time = System.currentTimeMillis() - start;
                        if( time < delay) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    stopAnim();
                                    Exception ex = result.getException();
                                    if(ex instanceof OuerException) {
                                        UtilOuer.toast(mActivity, ex.getMessage());
                                    } else {
                                        UtilOuer.toast(mActivity, R.string.play_start_niudan_failure);
                                    }
                                }
                            }, delay - time);
                        } else {
                            stopAnim();
                            Exception ex = result.getException();
                            if(ex instanceof OuerException) {
                                UtilOuer.toast(mActivity, ex.getMessage());
                            } else {
                                UtilOuer.toast(mActivity, R.string.play_start_niudan_failure);
                            }
                        }

                        OuerDispatcher.sendNiudanPlayBroadcast(mActivity);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        stopAnim();
                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 打开扭蛋中心界面
     */
    @OnClick(R.id.play_id_center)
    public void presetCenterActivity(){
        Animation curtainAnim = AnimationUtils.loadAnimation(mActivity,
                R.anim.res_translate_up_out);
        Animation playAnim = AnimationUtils.loadAnimation(mActivity,
                R.anim.res_translate_down_out);
        mRlCurtain.startAnimation(curtainAnim);
        mRlPlayRoot.startAnimation(playAnim);

        playAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mActivity.getSupportFragmentManager().popBackStack();
                setDoorVisible(true);
                OuerDispatcher.presentCenterFragment(mActivity);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    /**
     * 扭蛋
     */
    @OnClick(R.id.play_id_button)
    public void moekouPlay(){
        switch (mNiudanState) {
            case NIUDAN_STATE_ENABLE:
                if (!mIsPlaying) {
                    playAnim01();
                }
                break;
            case NIUDAN_STATE_DISABLE:
                UtilOuer.toast(mActivity, R.string.play_disable);
                break;
            case NIUDAN_STATE_UNKNOWN:
                niudanCheck();
                break;
            default:
                break;
        }
    }

    /**
     * 扭蛋选择
     */
    @OnClick(R.id.play_id_opts)
    public void moekouOpts(){
        onBackPressed();
    }

    /**
     * 我的图鉴
     */
    @OnClick(R.id.play_id_image)
    public void moekouMy() {
        flyOut(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mActivity.getSupportFragmentManager().popBackStack();
                OuerDispatcher.presentImageFragment(mActivity);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    private void playAnim01() {
        Animation anim01 = AnimationUtils.loadAnimation(mActivity,
                R.anim.moekou_play_rotate01);
        anim01.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                playAnim02();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mIvPlay.startAnimation(anim01);
    }

    private void playAnim02() {
        Animation anim02 = AnimationUtils.loadAnimation(mActivity,
                R.anim.moekou_play_rotate02);
        anim02.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                niudanStart();
                startAnim01();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mIvPlay.startAnimation(anim02);
    }

    /**
     * 扭蛋机动画01
     */
    private void startAnim01() {
        mIsPlaying = true;
        Animation anim01 = AnimationUtils.loadAnimation(mActivity,
                R.anim.play_machine_anim_01);
        anim01.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if(mIsPlaying) {
                    startAnim02();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mLlMachineRoot.startAnimation(anim01);
    }

    /**
     * 扭蛋机动画02
     */
    private void startAnim02() {
        Animation anim02 = AnimationUtils.loadAnimation(mActivity,
                R.anim.play_machine_anim_02);
        anim02.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if(mIsPlaying){
                    startAnim03();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mLlMachineRoot.startAnimation(anim02);
    }

    /**
     * 扭蛋机动画03
     */
    private void startAnim03() {
        Animation anim03 = AnimationUtils.loadAnimation(mActivity,
                R.anim.play_machine_anim_03);
        anim03.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if(mIsPlaying){
                    startAnim01();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mLlMachineRoot.startAnimation(anim03);
    }

    /**
     * 停止机动画
     */
    private void stopAnim() {
        mIsPlaying = false;
    }


    @Override
    public void onBackPressed() {
        flyOut(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mActivity.getSupportFragmentManager().popBackStack();
                setDoorVisible(true);
                openDoor(null);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 界面飞人
     * @param listener
     */
    private void flyIn(Animation.AnimationListener listener) {
        Animation curtainAnim = AnimationUtils.loadAnimation(mActivity,
                R.anim.res_translate_down_in);
        Animation playAnim = AnimationUtils.loadAnimation(mActivity,
                R.anim.res_translate_up_in);
        mRlCurtain.startAnimation(curtainAnim);
        mRlPlayRoot.startAnimation(playAnim);

        if(listener !=  null) {
            playAnim.setAnimationListener(listener);
        }
    }

    /**
     * 界面飞人
     * @param listener
     */
    private void flyOut(Animation.AnimationListener listener) {
        Animation curtainAnim = AnimationUtils.loadAnimation(mActivity,
                R.anim.res_translate_up_out);
        Animation playAnim = AnimationUtils.loadAnimation(mActivity,
                R.anim.res_translate_down_out);
        mRlCurtain.startAnimation(curtainAnim);
        mRlPlayRoot.startAnimation(playAnim);

        if(listener != null) {
            playAnim.setAnimationListener(listener);
        }
    }
}
